/**
 * Created by Laggo on 15/12/11.
 */
app.service('ajax', ['$q', '$http', 'SERVER_URL', 'toolService', '$state', '$sessionStorage', 'Upload', 'cAlert', 'toast', function ($q, $http, SERVER_URL, toolService, $state, $sessionStorage, Upload, cAlert, toast) {

    this.post = function (dataInput) {
        var req = {
            method: 'POST',
            url: SERVER_URL + dataInput.url,
            data: dataInput.data,
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            transformRequest: function(obj) {
                var str = [];
                for(var p in obj)
                    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                return str.join("&");
            },
        }
        return httpReq(req, dataInput);
    };
    this.get = function (dataInput) {
        var req = {
            method: 'GET',
            url: SERVER_URL + dataInput.url,
            params: dataInput.data
        }
        return httpReq(req, dataInput);
    }
    this.delete = function (dataInput, dataInput) {
        var req = {
            method: 'POST',
            url: SERVER_URL + dataInput.url,
            data: dataInput.data
        }
        return httpReq(req, dataInput);
    }

    function httpReq(req, dataInput) {
        if (dataInput.toast) {
            toast.create(dataInput.toast);
        }

        var deferred = $q.defer();
        $http(req).success(function (data, status, headers, config) {
            if (data.code == "0") {
                deferred.resolve(data.data, status, headers, config);
            } else {
                if (data.code == "1002") {
                    $state.go('login');
                } else {
                    cAlert.create({
                        mes: data.msg
                    });
                }
                deferred.reject(data, status, headers, config);
            }

        }).error(function (data, status, headers, config) {
            cAlert.create({
                mes:'服务器有问题,找陈强!'
            });
            deferred.reject(data, status, headers, config);
        });
        return deferred.promise;
    }

    this.upload = function (file) {
        var deferred = $q.defer();
        Upload.upload({
            //服务端接收
            url: SERVER_URL + '/cms/file/upload',
            //上传的同时带的参数
            data: {},

            file: file

        }).then(function (resp) {

            deferred.resolve(resp.data.data);

        }, function (resp) {

            console.log('Error status: ' + resp.status);

        }, function (evt) {
            var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
        });

        return deferred.promise;

    };


}]);
